import { defineStore } from 'pinia'
import { C91330326Ma287Bmm6JService, ProcessService, type C91330326MA287BMM6J_Service_GetWork,C91330326MA287BMM6J_Service_GetItem, type CreateProcessStepRequest, type ProcessStepRecord, type ProcessCardDetail } from '@/services';

interface AppState {
	work : C91330326MA287BMM6J_Service_GetWork | undefined,
	code : string | undefined,
	item:C91330326MA287BMM6J_Service_GetItem|undefined,
	processListCache: any[],
	processCardDetail: ProcessCardDetail | null
}

export default defineStore('app', {
	state: () : AppState => ({
		work: {
			events: []
		},
		item:{},
		code: '',
		processListCache: [],
		processCardDetail: null
	}),
	actions: {
		getEvents(step : number) {
			return this.work?.events?.filter(x => x.step == step) || [];
		},
		async loadWork() {
			let result = await C91330326Ma287Bmm6JService.apiC91330326Ma287Bmm6JWorkCodeGet(this.code);
			this.work = result.data;
		},
		async loadItem(){
			let result = await C91330326Ma287Bmm6JService.apiC91330326Ma287Bmm6JItemCodeGet(this.code);
			this.item = result.data;
		},
		// 加载工序列表并缓存
		async loadProcessList() {
			if (this.processListCache.length === 0) {
				try {
					const result = await ProcessService.getProcessList(1, 100);
					if (result.code === 200) {
						this.processListCache = result.rows.filter(item => item.dataStatus === 1);
					}
				} catch (error) {
					console.error('加载工序列表失败:', error);
				}
			}
			return this.processListCache;
		},
		// 根据工序名称获取工序ID
		getProcessIdByName(processName: string) {
			const process = this.processListCache.find(item => item.processName === processName);
			return process?.processId || null;
		},
		// 查询工序记录
		async getProcessStepRecord(processName: string): Promise<ProcessStepRecord | null> {
			await this.loadProcessList();
			const processId = this.getProcessIdByName(processName);
			
			if (!processId || !this.code) {
				return null;
			}

			try {
				const result = await ProcessService.getProcessStepByIds(this.code, processId);
				if (result.code === 200 && result.data) {
					return result.data;
				}
			} catch (error) {
				console.error('查询工序记录失败:', error);
			}
			return null;
		},
		// 创建工序记录
		async createProcessStep(processName: string, productionLength: number = 0, productionType: string = '标准生产'): Promise<boolean> {
			await this.loadProcessList();
			const processId = this.getProcessIdByName(processName);
			
			if (!processId || !this.code) {
				console.warn(`无法创建工序记录: processId=${processId}, code=${this.code}`);
				return false;
			}

			const request: CreateProcessStepRequest = {
				processCardId: this.code,
				processId: processId,
				productionType: productionType,
				productionLength: productionLength,
				productionTime: new Date().toISOString(),
				staffId: 1 // 暂时使用固定值，后续可以从用户信息中获取
			};

			try {
				const result = await ProcessService.createProcessStep(request);
				if (result.code === 200) {
					console.log('工序记录创建成功:', processName);
					return true;
				} else {
					console.error('工序记录创建失败:', result.msg);
					return false;
				}
			} catch (error) {
				console.error('工序记录创建失败:', error);
				return false;
			}
		},
		// 根据批次号加载流程卡详细信息
		async loadProcessCardDetail(batchNumber: string): Promise<boolean> {
			try {
				const result = await ProcessService.getProcessCardDetailByBatch(batchNumber);
				if (result.code === 200 && result.data) {
					this.processCardDetail = result.data;
					this.code = result.data.id; // 设置流程卡号
					console.log('流程卡详细信息加载成功:', result.data);
					return true;
				} else {
					console.error('流程卡详细信息加载失败:', result.msg);
					this.processCardDetail = null;
					return false;
				}
			} catch (error) {
				console.error('流程卡详细信息加载失败:', error);
				this.processCardDetail = null;
				return false;
			}
		}
	}
})